#include "tile_layer.h"
#include "texture_manager.h"
#include "tool.h"

using namespace alice;

TileLayer::TileLayer(int tile_size, int row, int columns, TileMap tile_map, TileSetList tile_sets):
  tile_size_(tile_size), row_(row), columns_(columns), tile_map_(tile_map), tile_sets_(tile_sets) {
    for (unsigned int i = 0; i < tile_sets_.size(); i++) {
      TextureManager::GetInstance()->Load(tile_sets_[i].name, Tool::CurrentPath() + "/res/maps/" + tile_sets_[i].source);
    }
  }

// TODO: 
// 在渲染地图瓦片的循环中添加输出语句时，
// 会导致程序运行时严重卡顿，原因不明。
void TileLayer::Render() {
  for (unsigned int i = 0; i < row_; i++) {
    for (unsigned int j = 0; j < columns_; j++) {
      int tile_id = tile_map_[i][j];
      if (tile_id == 0) {
        continue;
        
      } else {
        int tile_set_index = 0;

        if (tile_sets_.size() > 1) {
          for (unsigned int k = 0; k < tile_sets_.size(); k++) {
            if (tile_id > tile_sets_[k].first_id && tile_id < tile_sets_[k].last_id) {
              tile_id = tile_id - tile_sets_[k].first_id + 1;
              tile_set_index = k;
              break;
            }
          }
        }

        TileSet tile_set = tile_sets_[tile_set_index];
        int row = tile_id / tile_set.columns;
        int columns = tile_id - row * tile_set.columns - 1;

        if (tile_id % tile_set.columns == 0) {
          row -= 1;
          columns = tile_set.columns - 1;
        }

        TextureManager::GetInstance()->
          DrawTile(tile_set.name, j*tile_set.tile_size, i*tile_set.tile_size, tile_set.tile_size, row, columns);
      }
    }
  }
}

void TileLayer::Update() {

}